//
//  iCoreGUIController.m
//  TestFistGame
//
//  Created by  on 5/17/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "iCoreGUIController.h"
#import "VictoryScreen.h"
#import "IntroScreen.h"

@implementation iCoreGUIController

@synthesize isMuteSound, mainDirector, playerData, dataAccess, isPausingGame, listMap, currentMapRunning;

-(id)initiCoreGUIControllerWithDirector:(CCDirector *)_director {
    [super init];
    mainDirector = _director;
    dataAccess = [[DataAccess alloc]initDataAccess];
    
    playerData = [[PlayerData alloc]initUserDataWith:self];
    [self loadPlayerData];
    
    soundPlayer = [Sound getInstance];
    [self preloadSoundEffectFile:nil];
    isMuteSound = NO;
    
    isPausingGame = NO;
    
    listMap = [[NSArray alloc]initWithObjects:@"MapData/map_1.xml", @"MapData/map_2.xml", @"MapData/map_3.xml", @"MapData/map_4.xml", nil];
    currentMapRunning = 0;
    
    return self;
}

-(void)startUp {
    [self runGameScreen:GAME_SCREEN_INTRO];
}

-(void)runWithGameLayer:(GameLayer *)_gameLayer {
    CCScene *scene = [[CCScene alloc]init];
    [scene addChild:_gameLayer];
    
    if(mainDirector.runningScene == nil) {
        [mainDirector stopAnimation];//call this function fix fatal bug, open -> click home screen -> continue
        [mainDirector runWithScene:scene];
    } else {
        CCScene* transition =[CCTransitionFade transitionWithDuration:0.25f scene:scene];
        [mainDirector replaceScene:transition];
    }
    
    [scene release];
}

-(void)runGameScreen:(int)_gameScreenEnum {
    [self cleanupFrameCacheSprite];
    
    switch(_gameScreenEnum) {
        case GAME_SCREEN_INTRO:
        {
            IntroScreen *introScreen = [[IntroScreen alloc]initIntroScreenWith:self];
            [self runWithGameLayer:introScreen];
            [introScreen release];
            break;
        }
        case GAME_SCREEN_MAIN_MENU:
        {
            MainMenuScreen *mainMenuScreen = [[MainMenuScreen alloc]initWith:self];
            [self runWithGameLayer:mainMenuScreen];
            [mainMenuScreen release];
            break;
        }
        case GAME_SCREEN_SELECT_MAP:
        {
            MapScreen *mapScreen = [[MapScreen alloc]initWith:self];
            [self runWithGameLayer:mapScreen];
            [mapScreen release];
            break;
        }
        case GAME_SCREEN_PLAY:
        {            
            PlayScreen *playScreen = [[PlayScreen alloc]initPlayScreenWith:self withMapDataXmlFile:[listMap objectAtIndex:currentMapRunning]];
            [self runWithGameLayer:playScreen];
            [playScreen release];
            break;
        }
    }
}

-(void)startLoading:(int)_gameScreenEnum plistSpriteArr:(NSMutableArray *)_plistSpriteArr {
    NSMutableArray *list = [[NSMutableArray alloc]initWithObjects:PLIST_RESOURCE_GOBLIN,PLIST_RESOURCE_HERO,PLIST_RESOURCE_HOUND, PLIST_RESOURCE_GARGOYGLE, PLIST_RESOURCE_MAGIC_CIRCLE, PLIST_RESOURCE_MAGIC_RAY, PLIST_RESOURCE_HERO02, PLIST_RESOURCE_MAGIC_TOWER, PLIST_RESOURCE_SILVER_LIGHT, PLIST_RESOURCE_SILVER_LIGHT_EFFECT, PLIST_RESOURCE_STAR_EFFECT, PLIST_RESOURCE_STONE_BULLET, PLIST_RESOURCE_SUMMONER, PLIST_RESOURCE_THUNDER_LIGHT_EFFECT, PLIST_RESOURCE_FAST_TOWER, PLIST_RESOURCE_BARRACK_TOWER, PLIST_RESOURCE_BOOM_TOWER, PLIST_RESOURCE_BLOOD_C, PLIST_RESOURCE_FIRE_DROP, PLIST_RESOURCE_FIRE_DROP_EFFECT, PLIST_RESOURCE_SUMMONER, nil];
    
    LoadingScreen *loadingScreen = [[LoadingScreen alloc]initWith:self withGameScreenEnumNumber:_gameScreenEnum plistSpriteArr:list];
    
    CCScene *scene = [mainDirector runningScene];
    [scene addChild:loadingScreen z:10 tag:TAG_LOADING_SCREEN];
    
    [loadingScreen release];
}

-(void)loadGraphicFromPNGToFrameCache:(NSString *)_pngFileName withRowCount:(int)_rowCount withColumnCount:(int)_columnCount {
    CCSpriteBatchNode *batchNodeHero = [[CCSpriteBatchNode alloc]initWithFile:_pngFileName capacity:1];
    CGSize frameSize = CGSizeMake(batchNodeHero.texture.contentSize.width/_columnCount, batchNodeHero.texture.contentSize.height/_rowCount);
    for (int i=0; i<_rowCount; i++) 
        for (int j=0; j<_columnCount; j++) {
            CGRect rect = CGRectMake(j*frameSize.width, i*frameSize.height, frameSize.width, frameSize.height);
            CCSpriteFrame *frame = [[CCSpriteFrame alloc]initWithTexture:batchNodeHero.texture rect:rect];
            [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFrame:frame name:[NSString stringWithFormat:@"%@%d%d", _pngFileName, i, j]];
            [frame release];
            
        }
    [batchNodeHero release];
}

-(void)loadGraphicFromPlistFileToFrameCache:(NSString *)_plistFile {
    CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];
	[cache addSpriteFramesWithFile:_plistFile];
}

-(NSMutableArray*)loadAnimationWithNumberOfFrames:(int) numberOfFrames withFrameName:(NSString*)frame {
    NSMutableArray *anim = [[NSMutableArray alloc]init];
    for (int i = 0 ; i <= numberOfFrames ; i++)
    {
        NSString *frameName = [[NSString alloc]init];
        frameName = [NSString stringWithFormat:@"%@%d.png",frame,i];
        CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:frameName];
        [anim addObject:frame];
    }
    return anim;
}

-(CCAnimation *)loadAnimationFromCacheByName:(NSString *)_name withCount:(int)_frameCount delay:(float)_delay {
    CCAnimation *result = [[CCAnimationCache sharedAnimationCache] animationByName:_name];
    
    if(result == nil) {
        NSMutableArray *listFrameAnimation = [[NSMutableArray alloc]initWithArray:[self loadAnimationWithNumberOfFrames:_frameCount withFrameName:_name]];
        result = [CCAnimation animationWithFrames:listFrameAnimation delay:_delay];
        
        [[CCAnimationCache sharedAnimationCache] addAnimation:result name:_name];
        
        [listFrameAnimation removeAllObjects];
        [listFrameAnimation release];
    }
    
    return result;
}

-(BOOL)removeAnimationInFrameCache:(NSString *)_frameCacheName {
    BOOL isResult = NO;
    
    [[CCAnimationCache sharedAnimationCache] removeAnimationByName:_frameCacheName];
    
    if([[CCAnimationCache sharedAnimationCache] animationByName:_frameCacheName] == nil) {
        isResult = TRUE;
    }
    
    return isResult;
}

-(void)loadPlayerData {
    //get system config data
    //get system config setting from NSUSerDefault
    NSUserDefaults *dataStored = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *playerDataDictionary = [dataStored objectForKey:@"playerData"];
    if(!playerDataDictionary) {
        //if not exist in UserDefaultData, we will set default info
        playerData.playerName = @"New Player";
        //playerData.money = 300;
        //playerData.life = 10;
        playerData.star = 0;
    } else {
        [playerData loadDataFromDictionary:playerDataDictionary];
    }
}

-(void)pauseGameWithCurrentLayer:(GameLayer *)_currentLayer;{
    if(!isPausingGame) {
        [self setMuteSoundPlayer:YES];
        
        PauseGameScreen *pauseScreen = [[PauseGameScreen alloc]initPauseGameScreenWith:self withCurrentLayer:_currentLayer];
        CCScene *runningScene = [mainDirector runningScene];
        [runningScene addChild:pauseScreen z:100 tag:TAG_PAUSE_SCREEN];
        [mainDirector pause];
        
        isPausingGame = YES;
    }
}

-(void)resumeGame:(GameLayer *)_pauseGameScreen {    
    [mainDirector resume];
    
    [_pauseGameScreen removeFromParentAndCleanup:YES];
    [_pauseGameScreen release];

    [self setMuteSoundPlayer:NO];
    
    isPausingGame = NO;
}

-(void)cleanupFrameCacheSprite {
    //remove all image unused in cache
    [[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
    [[CCTextureCache sharedTextureCache] removeUnusedTextures];
}

-(void)connectGameCenter {
    NSLog(@"Authenticated Local User game center");
    [[GameCenterHelper shareInstance:self] authenticateLocalUser];
}

-(void)preloadSoundEffectFile:(NSString *)_fileName {
    [soundPlayer preloadSoundEffect:_fileName];
}

-(void)unloadSoundEffectFile:(NSString *)_fileName {
    [soundPlayer unloadSoundEffect:_fileName];
}

-(void)setEffectSoundVolume:(float)_value {
    [soundPlayer setEffectVolume:_value];
}

-(void)playBackgroundSound:(NSString *)_fileName withLoop:(BOOL)_isLoop {
    [self stopBackgroundSound];
    [self setEffectSoundVolume:0];
    [soundPlayer setMute:NO];
    [soundPlayer playBackgroundMusic:_fileName isLoop:_isLoop];
    [soundPlayer setMute:isMuteSound];
    [self setEffectSoundVolume:1];
}

-(void)playEffect:(NSString *)_fileName {
    [soundPlayer playEffect:_fileName];
}

-(void)stopBackgroundSound {
    [soundPlayer stopBackgroundMusic];
}

-(void)setBackgroundSoundVolume:(float)_value {
    [soundPlayer setBackgroundMusicVolume:_value];
}

-(void)setMuteSoundPlayer:(BOOL)_muteValue {
    isMuteSound = _muteValue;
    [soundPlayer setMute:_muteValue];
}

@end
